import jwt
import time
from flaskDemo.config.config import Config
#生成token
def generator_token(user):
    # 一天的过期时间
    timstamp = int(time.time()) + 24 * 60 * 60
    payload = {
        'id': user['id'],
        'username': user['user_name'],
        'exp': timstamp
    }
    key = Config.SECRET_KEY
    token = jwt.encode(payload, key=key, algorithm='HS256')
    return token

def verify_token(token):
    try:
        payload = jwt.decode(token, Config.SECRET_KEY, algorithms=["HS256"])
        userName = payload.get("user_name")
        userId = payload.get("id")
        return {"userName": userName,"id": userId}
    except jwt.PyJWTError:
        return 'token异常'
    except jwt.ExpiredSignatureError:
        return 'token过期'
    except jwt.DecodeError:
        return 'token认证失败'
    except jwt.InvalidTokenError:
        return '非法token'


if __name__ == "__main__":
    user = {'id':1,'user_name':'zhangsan'}
    token = generator_token(user)
    verify_token(token)



